<template>
  <view class="confirm-order">
    <!-- 地址 -->
    <view class="oder-map" @click="goToAddressPage">
        <template v-if="selectedAddress">
          <view class="map-title">
            <view class="map-name">收件人：{{selectedAddress.name}}</view>
            <view>{{selectedAddress.phone}}</view>
          </view>
          <view>收货地址：{{selectedAddress.province}}{{selectedAddress.city}}{{selectedAddress.town}}{{selectedAddress.address}}</view>
        </template>
        <!-- 如果没有选中的地址 -->
        <template v-else>
          <view class="map-title">
            <view class="map-name">请选择地址</view>
          </view>
        </template>
      </view>
      
    <!-- 商品 -->
    <view class="goods-list">
      <view class="goods-item">
        <view class="goods-text">
			 <image class="goods-img" :src="goodsInfo.images"></image>
          <view class="goods-name">{{ goodsInfo.name }}</view>
          <view class="goods-size">数量: {{ goodsInfo.quantity }}</view>
          <view class="goods-price">￥{{ goodsInfo.price }}</view>
        </view>
      </view>
    </view>
    
    <!-- 底部：提交订单 -->
    <view class="order-foot">
      <view class="foot-total">
        <view class="foot-count">合计：<text class="foot-count">￥{{ calculateTotalPrice }}</text></view>
        <view class="foot-num" @click="submitOrder" style="background-color: #f0f0f0; color: #7acfa6; padding: 15rpx 35rpx; font-size: 32rpx;">提交订单</view>
      </view>
    </view>
  </view>
</template>

<script>
import config from '@/config';

export default {
  data() {
    return {
      goodsInfo: {}, // 存储商品信息
      selectedAddress: null, // 存储选中地址信息
    };
  },
  computed: {
    calculateTotalPrice() {
      // 计算总价
      const price = parseFloat(this.goodsInfo.price);
      const quantity = parseInt(this.goodsInfo.quantity, 10);
      return (!isNaN(price) && !isNaN(quantity)) ? (price * quantity).toFixed(2) : '0.00';
    }
  },
  mounted() {
    this.getDefaultAddress();
    this.getGoodsInfo();
  },
  created() {
    // 监听自定义事件
    uni.$on('selectAddress', (address) => {
      this.selectedAddress = address; // 更新选中的地址数据
    });
  },
  methods: {
    getGoodsInfo() {
      // 从本地存储中获取商品信息
      const goods = uni.getStorageSync('goodsData');
      if (goods) {
        this.goodsInfo = goods;
      }
    },
    getDefaultAddress() {
      uni.request({
        url: config.apiUrl + '/address/getdefaultaddress',
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            this.selectedAddress = res.data;
          } else {
            console.error('Failed to fetch default address:', res);
          }
        },
        fail: (err) => {
          console.error('Request failed:', err);
        }
      });
    },
    goToAddressPage() {
      // 跳转到地址列表页面的方法
      uni.navigateTo({
        url: '/pages/mine/address/index2'
      });
    },
  submitOrder() {
     // 创建订单数据
     const order = {
       orderCount: this.goodsInfo.quantity || '1', // 如果商品没有 count 属性，默认为 1
       remark: '', // 可以填写备注
       orderState: '0', // 设置初始状态为 0
       orderPrice: this.goodsInfo.price,
       orderName: this.goodsInfo.name, // 商品名称作为订单名称 
       userId: this.selectedAddress ? this.selectedAddress.userId : null, // 从地址中获取用户 ID 
       nickName: this.selectedAddress ? this.selectedAddress.nickName : null, // 从地址中获取用户昵称 
       images: this.goodsInfo.images,
       shopId: this.goodsInfo.shopId
     };
  
     console.log('Order data before sending:', order);
  
     const totalPrice = this.calculateTotalPrice; // 直接使用计算属性，而不是调用方法
     uni.setStorageSync('totalPrice', totalPrice);  // 存储总价
  
     // 发送请求到后端 API
     uni.request({
       url: config.apiUrl + '/order/create',
       method: 'POST',
       data: [order],
       header: {
         'Content-Type': 'application/json'
       },
       success: (res) => {
         if (res.statusCode === 200) {
           const createdOrder = res.data[0]; // 获取创建成功的订单
           const orderId = createdOrder.orderId; // 获取订单 ID
 
           console.log('Created Order ID:', orderId); // 确认新创建订单的 ID
 
           uni.setStorageSync('orderIds', [orderId]); // 将订单ID存储到本地存储
 
           // 跳转到支付页面，并传递订单数据
           uni.navigateTo({
             url: `/pages/pay/goodspayment?orderId=${orderId}`
           });
         } else {
           uni.showToast({
             title: '提交订单失败',
             icon: 'none'
           });
         }
       },
       fail: (err) => {
         console.error('Request failed:', err);
         uni.showToast({
           title: '请求失败',
           icon: 'none'
         });
       }
     });
   }
  }
};
</script>

<style scoped>
.confirm-order {
  position: relative;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background-color: #f7f7f7;
}
.oder-map {
  padding: 20rpx;
  background-color: #ffffff;
  line-height: 40rpx;
}
.map-title {
  display: flex;
  justify-content: space-between;
}
.map-name {
  font-weight: bold;
}
.goods-list {
  margin-top: 20rpx;
  background-color: #ffffff;
  padding: 20rpx 0;
}
.goods-item {
  margin-top: 20rpx;
  padding: 10rpx 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f7f7f7;
}
.goods-text {
  width: 360rpx;
  padding: 0 10rpx;
  font-size: 26rpx;
}
.goods-img {
  width: 160rpx;
  height: 160rpx;
}
.goods-name {
  font-size: 26rpx;
}
.order-foot {
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  background-color: #ffffff;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.total-price {
  padding: 0 20rpx;
}
.price-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

</style>
